const msg = require('../database/tables/msg')
const user = require('../database/tables/user')
const { sequelize } = require('../database/init')
const rp = require('request-promise')
const { formatBody } = require('../tools')

msg.belongsTo(user, { foreignKey: 'from', targetKey: 'uid', as: 'fromUser' })

module.exports = {
  // async disconnect () {
    
  // },
  async joinGroup (info, socket, cb) {
    let { uid, nickname, groupId, avatar } = info
    console.log(info)
    const hasUser = await user.findOne({
      where: [{ uid: info.uid }]
    })
    let userInfo = info
    if (!hasUser) {
      await user.create({
        uid, nickname, avatar
      })
    } else {
      userInfo = await user.findOne({
        attributes: ['uid', 'nickname', 'avatar', 'foul_num', 'disable_time'],
        where: [
          { uid: uid }
        ]
      })
    }
    socket.join(groupId)
    return cb(formatBody(1, '加入成功', userInfo))
  },
  async groupMsg (info, socket, cb, io) {
    let { type, from, content, to } = info
    let spam = 1
    let fromUser = await user.findOne({
      where: [{ uid: from }],
      attributes: ['uid', 'nickname', 'avatar', 'foul_num', 'disable_time']
    })
    if (!fromUser) {
      return cb(formatBody(1, '发送失败，用户不存在'))
    }
    await rp({
      method: 'POST',
      uri: 'http://items.ufunet.cn/api/api?ifname=baidu.antispam',
      body: {
        content
      },
      json: true
    }).then(res => {
      console.log('groupMsg<>baidu.antispam=>res', res)
      spam = res.data.result.spam
    }).catch(err => {
      spam = 0
    })
    
    if (+spam === 0) {
      await msg.create({
        from,
        to,
        type,
        content
      })
      socket.broadcast.to(to).emit('groupMsg', {
        to, content, type, spam, fromUser
      })
    } else {
      let foul_num = fromUser.foul_num || 0
      fromUser.foul_num++
      foul_num++
      let disable_time_obj = {}
      // console.log('foul_num', foul_num)
      if (foul_num > 4) {
        disable_time_obj = {
          disable_time: new Date().getTime() + 1000 * 60 * 60 * 2
        }
        fromUser.disable_time = disable_time_obj.disable_time
        io.sockets.emit('foul', {
          fromUser,
          type: 1
        })
      }
      await user.update({
        foul_num,
        ...disable_time_obj
      }, {
        where: { uid: from }
      })
    }
    return cb(formatBody(1, '发送成功', {
      to, content, type, spam, fromUser
    }))
  },
  async getMsg (info, socket, cb, io) {
    let { limit, page } = info
    limit = limit || 20
    page = page || 1
    let offset = (page - 1) * limit
    let list = await msg.findAll({
      limit,
      offset,
      attributes: ['id', 'content', 'createdAt', 'type'],
      order: [
        ['createdAt', 'DESC']
      ],
      include: [
        {
          model: user,
          as: 'fromUser',
          attributes: ['nickname', 'avatar', 'uid']
        }
      ]
    })
    return cb(formatBody(1, 'ok', list.reverse()))
  },
  async foul (info, socket, cb, io) {
    let { uid, disable_time } = info
    let foulUser = await user.findOne({
      where: {
        uid
      }
    })
    disable_time = disable_time ? disable_time : 1000 * 60 * 60 * 2
    if (!foulUser) {
      return cb(formatBody(0, '用户不存在'))
    } else {
      await user.update({
        foul_num: 20,
        disable_time: new Date().getTime() + disable_time + ''
      }, {
        where: { uid }
      })
      let userInfo = await user.findOne({
        where: {
          uid
        }
      })
      io.sockets.emit('foul', {
        fromUser: userInfo,
        type: 2
      })
      return cb(formatBody(1, '禁言成功'))
    }
  },
  // 解除禁言
  async cancelFoul (info, socket, cb, io) {
    let { uid } = info
    await user.update({
      foul_num: null,
      disable_time: null
    }, {
      where: { uid: uid }
    })
    return cb(formatBody(1, 'ok'))
  }
}


